package com.agiantii.ablog.service.impl;

import com.agiantii.ablog.common.R;
import com.agiantii.ablog.config.FrontConfig;
import com.agiantii.ablog.pojo.dto.PostDTO;
import com.agiantii.ablog.pojo.Post;
import com.agiantii.ablog.pojo.User;
import com.agiantii.ablog.pojo.UserFollow;
import com.agiantii.ablog.handler.article.chain.ContentHandlerChain;
import com.agiantii.ablog.mapper.PostMapper;
import com.agiantii.ablog.mapper.UserMapper;
import com.agiantii.ablog.mapper.UserFollowMapper;
import com.agiantii.ablog.pojo.vo.PostVO;
import com.agiantii.ablog.service.PostService;
import com.agiantii.ablog.util.MailUtil;
import com.agiantii.ablog.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.agiantii.ablog.strategy.SearchStrategy;
import com.agiantii.ablog.enums.SearchTypeEnum;
import com.agiantii.ablog.handler.article.filter.ContentFilterManager;

@Slf4j
@Service
public class PostServiceImpl implements PostService {
    
    @Resource
    private PostMapper postMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private UserFollowMapper userFollowMapper;
    
    @Resource
    private ContentHandlerChain contentHandlerChain;
    
    @Resource
    private Map<String, SearchStrategy> searchStrategyMap;
    
    @Resource
    private ContentFilterManager contentFilterManager;


    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSenderImpl mailSender;

    @Override
    public R<PostVO> getPost(Long postId) {
        PostVO post = postMapper.findById(postId);
        if (post == null) {
            return R.error("文章不存在", 404);
        }
        return R.success(post, "获取文章成功");
    }
    
    @Override
    public R<List<PostVO>> getUserPosts(Long userId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<PostVO> posts = postMapper.findByUserId(userId);
        PageInfo<PostVO> pageInfo = new PageInfo<>(posts);
        return R.success(posts, "获取用户文章列表成功")
                .add("total", pageInfo.getTotal());
    }
    
    @Override
    public R<List<PostVO>> getAllPosts(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<PostVO> posts = postMapper.findAll();
        PageInfo<PostVO> pageInfo = new PageInfo<>(posts);
        return R.success(posts, "获取文章列表成功")
                .add("total", pageInfo.getTotal());
    }
    
    @Override
    public R<List<PostVO>> search(String keyword, String searchType, Integer page, Integer size) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return R.error("搜索关键词不能为空", 400);
        }
        
       
        SearchStrategy strategy = searchStrategyMap.get(searchType.toUpperCase());
        if (strategy == null) {
            return R.error("搜索类型不支持", 400);
        }
        
        PageHelper.startPage(page, size);
        List<PostVO> posts = strategy.search(keyword.trim());
        PageInfo<PostVO> pageInfo = new PageInfo<>(posts);
        
        return R.success(posts, "搜索成功").add("total", pageInfo.getTotal());
    }
    
    @Override
    public R<Post> createPost(Long userId, PostDTO postDTO) {
        try {
            // 获取作者信息
            User author = userMapper.findById(userId);
            if (author == null) {
                return R.error("用户不存在", 400);
            }
            
            // 使用过滤器进行内容审核
            contentFilterManager.filterContent(postDTO);
            
            // 创建文章
            Post post = new Post();
            BeanUtils.copyProperties(postDTO, post);
            post.setUserId(userId);
            postMapper.insert(post);
            
            // 获取所有粉丝
            List<UserFollow> followers = userFollowMapper.findByFollowingId(userId);
            if (!followers.isEmpty()) {
                // 获取粉丝的用户信息
                List<Long> followerIds = followers.stream()
                        .map(UserFollow::getFollowerId)
                        .collect(Collectors.toList());
                List<User> users = userMapper.findByIds(followerIds);
                
                // 发送邮件通知粉丝
                for (User follower : users) {
                    String emailContent = String.format(
                        "您关注的作者 %s 发布了新文章《%s》，快去看吧 <a href='%s'>%s</a>",
                        author.getUsername(),
                        postDTO.getTitle(), FrontConfig.POST_URL+post.getId(),
                            postDTO.getTitle()
                    );
                    log.info(emailContent);
                    if (StringUtil.isEmpty(follower.getEmail())) {
                        log.error("邮件内容为空");
                        continue;
                    }
                    try {

                        SimpleMailMessage msg = new SimpleMailMessage();
                        msg.setFrom(from);
                        msg.setTo(follower.getEmail());
                        msg.setSubject("有新文章发布");
                        msg.setText(emailContent);
                        mailSender.send(msg);
                    } catch (Exception e) {
                        log.error("邮件发送异常 to:{}, error:{}", follower.getEmail(), e.getMessage());
                    }
                }
            }
            
            return R.success(post, "发布成功");
        } catch (IllegalArgumentException e) {
            return R.error(e.getMessage(), 400);
        }
    }
    
    @Override
    public R<PostVO> updatePost(Long postId, Long userId, PostDTO postDTO) {
        PostVO post = postMapper.findById(postId);
        if (post == null) {
            return R.error("文章不存在", 404);
        }
        if (!post.getUserId().equals(userId)) {
            return R.error("无权修改此文章", 403);
        }
        
        post.setTitle(postDTO.getTitle());
        post.setContent(postDTO.getContent());
        post.setCover(postDTO.getCover());
        postMapper.update(post);


        return R.success(post, "更新成功");
    }
    
    @Override
    public R<Void> deletePost(Long postId, Long userId) {
        PostVO post = postMapper.findById(postId);
        if (post == null) {
            return R.error("文章不存在", 404);
        }
        if (!post.getUserId().equals(userId)) {
            return R.error("无权删除此文章", 403);
        }
        
        postMapper.deleteById(postId);
        return R.success("删除成功");
    }
} 